﻿using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;

namespace Asion.Dapper
{
    public static class SqlBulkCopyHelper
    {
        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="tableName"></param>
        /// <param name="sourceTable"></param>
        /// <returns></returns>
        public static void BatchInsert(SqlConnection connection, string tableName, DataTable sourceTable)
        {
            using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connection))
            {
                sqlBulkCopy.DestinationTableName = tableName;
                sqlBulkCopy.BulkCopyTimeout = 120;
                for (int i = 0; i < sourceTable.Columns.Count; i++)
                {
                    string columnName = sourceTable.Columns[i].ColumnName;
                    sqlBulkCopy.ColumnMappings.Add(columnName, columnName);
                }
                sqlBulkCopy.WriteToServer(sourceTable);
            }
        }
    }
}
